package depta.dataregion;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.htmlparser.Node;
import org.htmlparser.util.NodeList;


import util.nodecloner.ChildFinder;
import util.nodecloner.NodeCloner;

public class DataRegion {

	private Node node;
	private int[] DR;
	private List<Node> generalizedNodes;
	private int comb;

	public DataRegion(int[] maxDR, Node node2) {
				
		this.node = node2;
		
		this.DR = new int[3];
		
		DR[0] = maxDR[0];
		DR[1] = maxDR[1];
		DR[2] = maxDR[2];
		
		this.comb = maxDR[0];
		
		generalizedNodes = new ArrayList<Node>();
		
		Node parent = null;
		
		for (int i = DR[1]; i < DR[1] + DR[2]; i++) {
			
			if (((i - DR[1]) % comb) == 0){
				parent = NodeCloner.clone(node2, false, false);
				generalizedNodes.add(parent);
			}
			
			Node toCopy = NodeCloner.clone(ChildFinder.getChildren(node2).elementAt(i),true,true);
			
			ChildFinder.getChildren(parent).add(toCopy);
			
		}
		
	}

	public boolean inRange(int index) {
		
		return (DR[1] <= index) && (index <= DR[1]+DR[2]-1);
		
	}

	public List<Node> getGeneralizedNodes() {
		return generalizedNodes;
	}
	
	public String toString(){
		
		String t = "";
		
		for (Node geneNode : generalizedNodes) {
			
			t = t + "\n<br>\n" + getString(geneNode);
			
		}
		
		return t;
	}

	private String getString(Node geneNode) {

		NodeList ch = ChildFinder.getChildren(geneNode);
		
		String ret = "";
		
		for (int i = 0; i < ch.size(); i++) {
			
			ret += "\n<br>\n" + ch.elementAt(i).toHtml();
			
		}
		
		return ret;
		// Use a Transformer for output
//		TransformerFactory tFactory =
//				TransformerFactory.newInstance();
//		Transformer transformer;
//		try {
//
//			DOMSource source = new DOMSource(geneNode);
//			
//			StringWriter sw = new StringWriter();
//			
//			StreamResult result = new StreamResult(sw);
//
//			transformer = tFactory.newTransformer();
//			
//			transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
//			
//			transformer.transform(source, result);
//
//			return sw.toString();
//			
//		} catch (TransformerConfigurationException e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//		} catch (TransformerException e2) {
//			// TODO Auto-generated catch block
//			e2.printStackTrace();
//		}
//
//		return "";
	}

}
